import { cloneVNode, isVNode } from 'vue';

// 深度规范化子节点
function normalizeChildNodes(children, params) {
  return children.flatMap(child => {
    // 处理函数类型子元素
    if (typeof child.type === 'symbol' && child.children) {
      return normalizeChildNodes(child.children);
    }
    // 处理数组嵌套
    if (Array.isArray(child)) {
      return normalizeChildNodes(child);
    }
    // 过滤非VNode元素
    return isVNode(child) ? [child] : [];
  });
}
function useChildren({
  slots,
  props,
  sameType,
  transform
}) {
  // 获取规范化后的子节点数组
  const children = slots.default?.() || [];
  const normalizedChildren = normalizeChildNodes(children);

  // 类型校验和过滤
  const validChildren = normalizedChildren.filter(child => {
    const isValid = !sameType || child.type === sameType;
    return isValid;
  });

  // 处理props合并
  const processedChildren = validChildren.map((child, index) => {
    let transferedProps = {};
    if (transform) {
      transferedProps = transform(child.props, index);
    }
    // 创建新的props对象
    const mergedProps = {
      ...child.props,
      ...props,
      // 自动注入索引值
      index,
      ...transferedProps
    };

    // 克隆并应用新props
    return cloneVNode(child, mergedProps);
  });
  return processedChildren;
}

export { useChildren as default };
